//
//  UIImage+Extension.swift
//  SectionCorner
//
//  Created by han on 2019/7/19.
//  Copyright © 2019 han. All rights reserved.
//

import UIKit

extension UIImage: HeadlineExtensionProtocol {}
extension HeadlineExtended where T: UIImage {
    
    /// image圆角
    func drawCorner(radius: CGFloat, size: CGSize) -> UIImage? {
        let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
        UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext()
        let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
        context?.addPath(bezierPath.cgPath)
        context?.clip()
        context?.drawPath(using: .fillStroke)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image
    }
    
    /// 异步设置圆角图片
    func drawCornerAsync(size: CGSize, radius: CGFloat, completion:@escaping (_ image:UIImage?)-> Void ){
        DispatchQueue.global().async {
            let rect = CGRect(x: 0, y: 0, width: size.width, height: size.height)
            UIGraphicsBeginImageContextWithOptions(size, false, UIScreen.main.scale)
            let context = UIGraphicsGetCurrentContext()
            let bezierPath = UIBezierPath(roundedRect: rect, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
            context?.addPath(bezierPath.cgPath)
            context?.clip()
            context?.drawPath(using: .fillStroke)
            let image = UIGraphicsGetImageFromCurrentImageContext()
            UIGraphicsEndImageContext()
            DispatchQueue.main.async{
                completion(image)
            }
        }
    }
    
    /// 绘制纯色Image
    static func drawImage(with color: UIColor, frame: CGRect) -> UIImage? {
        UIGraphicsBeginImageContextWithOptions(frame.size, false, UIScreen.main.scale)
        let context = UIGraphicsGetCurrentContext();
        context?.setFillColor(color.cgColor)
        context?.fill(frame)
        let image = UIGraphicsGetImageFromCurrentImageContext();
        UIGraphicsEndImageContext();
        return image
    }
    
    
    /// ImageSize的Pixel大小
    var sizeInPixel: CGSize {
        return CGSize(width: value.size.width * value.scale, height: value.size.height * value.scale)
    }
  
    /// 判断是否存在透明通道
    var isOpaque: Bool {
        let alphaInfo = value.cgImage?.alphaInfo
        return  alphaInfo == .noneSkipLast || alphaInfo == . noneSkipFirst || alphaInfo == .none
    }
    
}
